package ink.teamwork.battery.service

import ink.teamwork.battery.entity.Coupon
import ink.teamwork.battery.model.Result
import ink.teamwork.battery.model.UserCoupon
import ink.teamwork.battery.repository.CouponRepository
import ink.teamwork.battery.repository.UserRepository
import ink.teamwork.battery.util.IdWorker
import org.springframework.data.domain.Sort
import org.springframework.stereotype.Service
import java.time.LocalDateTime

@Service
class CouponService : JdbcService() {

    lateinit var userRepository: UserRepository

    lateinit var couponRepository: CouponRepository

    fun send(openId: String): Result {
        val inviteUserList = userRepository.findAllByVid(openId, Sort.unsorted())
        val couponList = couponRepository.findAllByOpenId(openId, Sort.unsorted())
        if (inviteUserList.size < 10) {
            return Result.error("请邀请10位好友")
        }
        if (couponList.size > inviteUserList.size % 10) {
            return Result.error("邀请人数不足, 无法发放")
        }
        val coupon = Coupon()

        coupon.id = IdWorker.getNextId()
        coupon.openId = openId
        coupon.value = 100
        coupon.used = false
        coupon.createdAt = LocalDateTime.now()
        coupon.updatedAt = LocalDateTime.now()
        couponRepository.save(coupon)
        return Result.success("发放成功")
    }

    fun getCouponList(openId: String): List<Coupon> {
        return couponRepository.findAllByOpenId(openId, Sort.by(Sort.Order.desc("createdAt")))
    }

    fun getUserCouponList(): List<UserCoupon> {
        val sql =
            "SELECT u.open_id, u.nickname, u.avatar, i.inviteUserCount, c.couponCount, (i.inviteUserCount%10-c.couponCount)  unsendCouponCount  FROM user u LEFT JOIN (SELECT COUNT(1) couponCount, open_id FROM coupon c GROUP BY open_id) c ON u.open_id = c.open_id LEFT JOIN (SELECT COUNT(1) inviteUserCount, vid FROM user GROUP BY vid) i ON u.open_id = i.vid ORDER BY unsendCouponCount DESC"
        return queryForList(sql, UserCoupon::class.java)
    }

}